package cn.maihe.elg.operation.service.system.impl;

import cn.maihe.elg.operation.repository.entity.PermissionDO;
import cn.maihe.elg.operation.repository.entity.RoleDO;
import cn.maihe.elg.operation.repository.entity.entityCustom.PermissionDOCustom;
import cn.maihe.elg.operation.repository.entity.entityCustom.RoleDOCustom;
import cn.maihe.elg.operation.repository.mapper.PermissionMapper;
import cn.maihe.elg.operation.repository.mapper.RoleMapper;
import cn.maihe.elg.operation.service.system.PermissionService;
import cn.maihe.elg.operation.service.system.UserService;
import cn.maihe.elg.operation.utils.PermissionHelper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author JHWei on 2018-07-13.
 * @ 创建日期：2018-07-13
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserService userService;

    @Override
    public List<PermissionDOCustom> getAll() {
        //查询所有权限列表
//        EntityWrapper ew = new EntityWrapper();
//        ew.setEntity(new PermissionDO());
        List<PermissionDOCustom> permissionList = permissionMapper.selectListAll();
        //处理数据
        return PermissionHelper.listToTree(permissionList);
    }

    @Override
    public List<PermissionDO> getPermissionList() {
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new PermissionDO());
        List<PermissionDO> permissionList = permissionMapper.selectList(ew);
        return permissionList;
    }

    @Override
    public List<String> queryPermissionByUserId() {
        //根据用户id查询当前用户的所有角色
        String userIdString = userService.getUserContext().getId();
        Long userId = Long.parseLong(userIdString);
        List<RoleDOCustom> userRoles = roleMapper.findByUserId(userId);
        if (CollectionUtils.isEmpty(userRoles)) {
            return null;
        }
        //根据角色id查询当前角色的所有权限列表
        List<String> list = new ArrayList<>();
        for (RoleDO role : userRoles) {
            List<PermissionDOCustom> permissionList = permissionMapper.findByRoleId(role.getId());
            for (PermissionDO permissionDO : permissionList) {
                list.add(permissionDO.getPath());
            }
        }
        return list.stream().distinct().collect(Collectors.toList());
    }

}
